package com.osfw.system.service.monitor.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.osfw.framework.enums.DateStyle;
import com.osfw.framework.utils.DateUtils;
import com.osfw.framework.utils.StringUtils;
import com.osfw.system.entity.monitor.SysOperLog;
import com.osfw.system.entity.monitor.SysUserOnline;
import com.osfw.system.mapper.monitor.SysOperLogMapper;
import com.osfw.system.mapper.monitor.SysUserOnlineMapper;
import com.osfw.system.service.monitor.ISysUserOnlineService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

/**
 * 在线用户 服务层处理
 */
@Service
public class SysUserOnlineServiceImpl extends ServiceImpl<SysUserOnlineMapper, SysUserOnline> implements ISysUserOnlineService {
    @Autowired
    private SysUserOnlineMapper userOnlineDao;

    /**
     * 通过会话序号查询信息
     *
     * @param sessionId 会话ID
     * @return 在线用户信息
     */
    @Override
    public SysUserOnline selectOnlineById(String sessionId) {
        return getById(sessionId);
    }

    /**
     * 通过会话序号删除信息
     *
     * @param sessionId 会话ID
     * @return 在线用户信息
     */
    @Override
    public void deleteOnlineById(String sessionId) {
        removeById(sessionId);
    }

    /**
     * 通过会话序号删除信息
     *
     * @param sessions 会话ID集合
     * @return 在线用户信息
     */
    @Override
    public void batchDeleteOnline(List<String> sessions) {
        removeByIds(sessions);
    }

    /**
     * 保存会话信息
     *
     * @param online 会话信息
     */
    @Override
    public void saveOnline(SysUserOnline online) {
        saveOrUpdate(online);
    }

    /**
     * 查询会话集合
     *
     * @param userOnline 在线用户
     */
    @Override
    public List<SysUserOnline> selectUserOnlineList(SysUserOnline userOnline) {
        LambdaQueryWrapper<SysUserOnline> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.like(StringUtils.isNotEmpty(userOnline.getIpaddr()), SysUserOnline::getIpaddr, userOnline.getIpaddr());
        queryWrapper.like(StringUtils.isNotEmpty(userOnline.getLoginName()), SysUserOnline::getLoginName, userOnline.getLoginName());
        return list(queryWrapper);
    }

    /**
     * 强退用户
     *
     * @param sessionId 会话ID
     */
    @Override
    public void forceLogout(String sessionId) {
        removeById(sessionId);
    }

    /**
     * 查询会话集合
     *
     * @param expiredDate 失效日期
     */
    @Override
    public List<SysUserOnline> selectOnlineByExpired(Date expiredDate) {
        LambdaQueryWrapper<SysUserOnline> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.le(SysUserOnline::getLastAccessTime, expiredDate);
        queryWrapper.orderByAsc(SysUserOnline::getLastAccessTime);
        return list(queryWrapper);
    }
}
